'use strict'
// http://blog.csdn.net/lbxx1984/article/details/40988337
// https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas
export default function () {
  const w = this

  w.WW = window.innerWidth
  w.HH = window.innerHeight
  w.svg = ''

  const canvas = document.getElementById('canvas')
  canvas.width = w.WW
  canvas.height = w.HH

  let DOMURL = window.URL || window.webkitURL || window
  let mW = 368,
      mH = 226,
      sX = (w.WW - mW) / 2 >> 0,
      sY = (w.HH - mH) / 2

  let ctx = canvas.getContext('2d')

  w._init = () => {
    // w.load('./eye.svg')
    w.createEye()
  }

  w.createBox = (img) => {
    ctx.rect(sX, sY, mW, mH);
    ctx.fillStyle = '#fff'
    ctx.fill()
    ctx.drawImage(img, 0, 0, mW, mH, sX, sY, mW, mH)
  }

  /**
   * 通过此方法，可将 DOM 插入 canvas
   * @param url
   */
  w.load = (url) => {
    let reguest = new XMLHttpRequest()
    reguest.open('get', url, true)
    reguest.responseType = 'text'
    reguest.onload = () => {
      w.svg = reguest.response

      let img = new Image();
      let svg = new Blob([w.svg], {type: 'image/svg+xml;charset=utf-8'})
      let url = DOMURL.createObjectURL(svg)
      img.src = url
      img.onload = () => {
        w.createBox(img)
        DOMURL.revokeObjectURL(url);
      }
    }
    reguest.send()
  }

  w.createEye = () => {
    let s_x = sX,
        s_y = sY + mH / 2,
        e_x = sX + mW,
        e_y = s_y

    ctx.beginPath()
    ctx.moveTo(sX, s_y)
    ctx.bezierCurveTo(
        sX + 40, sY - 20,
        sX + mW - 40, sY - 20,
        e_x, e_y)
    ctx.bezierCurveTo(
        e_x - 40, sY + mH + 20,
        s_x + 40, sY + mH + 20,
        s_x, s_y)
    ctx.strokeStyle = 'red'
    ctx.stroke()
  }

  w._init()
}